package com.uex.dev.manage.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import com.uex.dev.manage.admin.config.MiniserveConfig;
import com.uex.dev.manage.admin.dao.DeviceImgDao;
import com.uex.dev.manage.admin.enums.DeviceTypeEnum;
import com.uex.dev.manage.admin.po.DeviceImgPO;
import com.uex.dev.manage.admin.po.DeviceModelPO;
import com.uex.dev.manage.admin.service.IDeviceImgService;
import com.uex.dev.manage.admin.service.IDeviceModelService;
import com.uex.dev.manage.admin.utils.LogUtil;
import com.uex.dev.manage.admin.vo.device.DeviceImgResp;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangchao
 * @since 2024-02-22
 */
@Slf4j
@Service
public class DeviceImgServiceImpl extends ServiceImpl<DeviceImgDao, DeviceImgPO> implements IDeviceImgService {

    @Resource
    private IDeviceModelService deviceModelService;

    @Resource
    private MiniserveConfig miniserveConfig;

    @Override
    public Boolean addDeviceImg(DeviceImgPO deviceAddImgReq) {
        LambdaQueryWrapper<DeviceModelPO> wrapper = new LambdaQueryWrapper<DeviceModelPO>()
                .eq(DeviceModelPO::getDeviceType, deviceAddImgReq.getDeviceType())
                .eq(DeviceModelPO::getDeviceModel, deviceAddImgReq.getDeviceModel());
        Preconditions.checkArgument(Objects.nonNull(deviceModelService.getOne(wrapper)), "设备型号不存在");
        // 拼接路径
        String Path = miniserveConfig.getImg().replace("{devType}", deviceAddImgReq.getDeviceType().toString())
                                  .replace("{devModel}", deviceAddImgReq.getDeviceModel()) +
                          deviceAddImgReq.getImgUrl();
        String LocalPath = miniserveConfig.getPath() + Path;
        // 文件重命名
        File file = new File(LocalPath);
        // 判断文件是否存在
        Preconditions.checkArgument(file.exists(), "文件不存在或上传失败");
        String suffix = FilenameUtils.getExtension(file.getName());
        String newFileName = LocalPath.replace(file.getName(), UUID.randomUUID() + "." + suffix);
        file.renameTo(new File(newFileName));
        // 切换为miniserve路径
        String url = newFileName.replace(miniserveConfig.getPath(), miniserveConfig.getUrl());
        DeviceImgPO deviceImg = new DeviceImgPO();
        BeanUtils.copyProperties(deviceAddImgReq, deviceImg);
        deviceImg.setImgUrl(url);
        this.save(deviceImg);
        LogUtil.log(0, String.format("添加%s类型%s型号图片", deviceAddImgReq.getDeviceType(), deviceAddImgReq.getDeviceModel()));
        return true;
    }

    @Override
    public Boolean delDeviceImg(Integer id) {
        DeviceImgPO devImg = this.getById(id);
        Preconditions.checkArgument(ObjectUtils.isNotNull(devImg), "图片不存在");
        String path = devImg.getImgUrl().replace(miniserveConfig.getUrl(), miniserveConfig.getPath());
        File file = new File(path);
        boolean deleted = file.delete();
        if (!deleted) {
            log.error("[DeviceImg] Failed to delete the file {}", path);
        }
        LogUtil.log(0, String.format("删除Id %d 图片", id));
        return this.removeById(id);
    }

    @Override
    public List<DeviceImgResp> selectList(DeviceTypeEnum deviceType, String deviceModel) {
        ArrayList<DeviceImgResp> imgList = new ArrayList<>();
        LambdaQueryWrapper<DeviceImgPO> wrapper = new LambdaQueryWrapper<DeviceImgPO>()
                .eq(DeviceImgPO::getDeviceType, deviceType)
                .eq(StringUtils.isNotEmpty(deviceModel),DeviceImgPO::getDeviceModel, deviceModel)
                .orderByDesc(DeviceImgPO::getId);
        List<DeviceImgPO> list = this.list(wrapper);
        list.forEach(x -> {
            DeviceImgResp deviceImgResp = new DeviceImgResp();
            deviceImgResp.setImgId(x.getId());
            deviceImgResp.setImgName(x.getImgName());
            deviceImgResp.setImgUrl(x.getImgUrl());
            imgList.add(deviceImgResp);
        });
        LogUtil.log(0, String.format("获取%s类型%s型号的图像列表", deviceType, deviceModel));
        return imgList;
    }
}
